//
//  BONSTimerQueue.m
//  Bourse
//
//  Created by 俊松何 on 2018/1/25.
//  Copyright © 2018年 tianxie. All rights reserved.
//

#import "BONSTimerQueue.h"

@implementation BOQueueModel


@end

@interface BONSTimerQueue()
@property(nonatomic,strong) NSTimer *timer;
@property(nonatomic,strong) NSMutableDictionary *enevtDict;

@end


static BONSTimerQueue *queuetimer=nil; //放入外部
@implementation BONSTimerQueue
+(instancetype)shareTimer
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        queuetimer = [[BONSTimerQueue alloc] init];
        queuetimer.enevtDict = [NSMutableDictionary dictionaryWithCapacity:10];
    });
    return queuetimer;
}
-(void)startTimer
{
    _timer = [NSTimer timerWithTimeInterval:0.5 target:self selector:@selector(timerClick) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
    
}
-(void)timerClick
{
    if([self.enevtDict allKeys].count == 0)
    {
        [_timer invalidate];
        _timer = nil;
        return;
    }
    [self.enevtDict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, BOQueueModel  *obj, BOOL * _Nonnull stop) {
        obj.currentTime = obj.currentTime + 0.5;
        if(obj.currentTime - obj.oldTime >= obj.time)
        {
            if([obj.target respondsToSelector:obj.selector])
            {
                [obj.target performSelector:obj.selector];
            }
            obj.oldTime =  obj.currentTime;
        }
    }];
}



-(void)addEvent:(SEL)selector target:(NSObject *)target timerWithTimeInterval:(NSTimeInterval)timer
{
    if(_timer == nil)
    {
        [self startTimer];
    }

    NSString *uniqueid = [NSString stringWithFormat:@"%@-%@",target,NSStringFromSelector(selector)];
    BOQueueModel *model = [BOQueueModel new];
    model.time = timer;
    model.selector = selector;
    model.uniqueId = uniqueid;
    model.target = target;
    [self.enevtDict setObject:model forKey:uniqueid];
}


-(void)removeEcvent:(SEL)selector target:(NSObject *)target
{
    NSString *uniqueid = [NSString stringWithFormat:@"%@-%@",target,NSStringFromSelector(selector)];
     [self.enevtDict removeObjectForKey:uniqueid];
}




@end
